//
//  simple-presenter
//
//  Created by Francisco Silva on 7/16/11.
//  Copyright 2011 Francisco Silva. All rights reserved.
//

#import "FSSimplePresenter.h"

@implementation FSSimplePresenter

@synthesize window;
@synthesize projector;

@synthesize windowView;

@synthesize thumbnailContainer;

@synthesize projectorImage;
@synthesize projectorMovie;

@synthesize scrollImages;
@synthesize scrollVideos;
@synthesize scrollThumbnails;

@synthesize tableImages;
@synthesize tableVideos;

@synthesize playPauseButton;
@synthesize stopButton;
@synthesize moreZoomButton;
@synthesize lessZoomButton;
@synthesize moreHeightButton;
@synthesize lessHeightButton;
@synthesize moreWidthButton;
@synthesize lessWidthButton;
@synthesize leftButton;
@synthesize rightButton;
@synthesize upButton;
@synthesize downButton;
@synthesize blankButton;

- (void)positionProjector
{
    NSScreen* mainScreen = [[NSScreen screens] objectAtIndex:0];
    
    if([[NSScreen screens] count] > 1)
    {
        NSScreen* secondaryScreen = [[NSScreen screens] objectAtIndex:1];
        
        // DUAL SCREEN -> PRESENT IN FULL SCREEN
        [projector setFrame:NSMakeRect([mainScreen frame].size.width, 
                                       0, 
                                       [secondaryScreen frame].size.width, 
                                       [secondaryScreen frame].size.height) 
                    display:true];
        
        [window setFrame:NSMakeRect(0, 
                                    178, 
                                    [mainScreen frame].size.width, 
                                    [mainScreen frame].size.height) 
                 display:TRUE];
    }
    else
    {
        // SINGLE SCREEN -> PRESENT IN THE RIGHT SIDE OF THE SCREEN
        [projector setFrame:NSMakeRect(640, 178, 640, 600) display:true];
        [window setFrame:NSMakeRect(0, 178, 640, 600) display:TRUE];
    }
    
    [projector setLevel:kCGMaximumWindowLevel];
    //[window setLevel:kCGMaximumWindowLevel];
    [projectorMovie setFrame:[projectorImage frame]];
}

- (void)loadMusicFolder
{
    musicNames = [FSSimplePresenter getSortedContentsOf:musicFolder];
    
    slides = [[NSMutableDictionary alloc] init];
    
    for(NSString *musicName in musicNames)
    {
        NSString *musicPath = [[NSString alloc] 
                               initWithFormat:@"%@%@", musicFolder, musicName];
        
        NSMutableArray *musicImages = [[NSMutableArray alloc] init];
        
        for(NSString *imageName in [FSSimplePresenter getSortedContentsOf:musicPath])
        {
            if([imageName rangeOfString:@".jpg"].location == NSNotFound)
            {
                continue;
            }
            
            NSString *imagePath = [[NSString alloc] initWithFormat:@"%@%@/%@", 
                                   musicFolder, musicName, imageName];
            
            [musicImages addObject:[[NSImage alloc] initByReferencingFile:imagePath]];
        }
        
        [slides setValue:musicImages forKey:musicName];
    }
}

- (void)loadVideoFolder
{
    movieNames = [[NSMutableArray alloc] init];
    
    for(NSString* movie in [FSSimplePresenter getSortedContentsOf:movieFolder])
    {
        if([movie rangeOfString:@".avi"].location == NSNotFound &&
           [movie rangeOfString:@".wmv"].location == NSNotFound)
        {
            continue;
        }
        
        [movieNames addObject:movie];
    }
}

- (void)loadConfiguration
{
    musicFolder = [[NSString alloc] initWithString: @"/musicas/"];
    movieFolder = [[NSString alloc] initWithString: @"/videos/"];
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    [self positionProjector];
}

//called once the nib is loaded and all outlets are available
- (void)awakeFromNib
{        
    [self loadConfiguration];
    [self loadMusicFolder];
    [self loadVideoFolder];
}

- (int)numberOfRowsInTableView:(NSTableView *)tableView
{
    if([tableView isEqualTo:tableImages])
        return (int)[musicNames count];
    else
        return (int)[movieNames count];
}

- (id)tableView:(NSTableView *)tableView
objectValueForTableColumn:(NSTableColumn *)tableColumn
            row:(int)row
{
    if([tableView isEqualTo:tableImages])
        return [musicNames objectAtIndex:row];
    else
        return [movieNames objectAtIndex:row];
}

- (IBAction)tableViewSelected:(id)sender
{
    if([sender isEqualTo:tableImages])
    {        
        while([[thumbnailContainer subviews] count] > 0)
        {
            [[[thumbnailContainer subviews] objectAtIndex:0] removeFromSuperview];
        }
        
        int row = (int)[sender selectedRow];
        
        NSString *musicName =  (NSString*)[musicNames objectAtIndex:row];
        
        for(NSImage *image in [slides valueForKey:musicName])
        {
            [self addButtonForImage:image];
        }
        
        [self redistributeImages];
        
        [projectorImage setHidden:FALSE];
        [projectorMovie setHidden:TRUE];
        [playPauseButton setEnabled:FALSE];
        [stopButton setEnabled:FALSE];
    }
    else
    {        
        while([[thumbnailContainer subviews] count] > 0)
        {
            [[[thumbnailContainer subviews] objectAtIndex:0] removeFromSuperview];
        }
        
        int row = (int)[sender selectedRow];
        
        NSString *movieName = [[NSString alloc] initWithFormat:@"%@%@", 
                               movieFolder,
                               [movieNames objectAtIndex:row]];

        NSError *e;
        
        QTMovie *movie = [[QTMovie alloc] initWithFile:movieName error:&e];
        
        [projectorMovie setMovie:movie];
        
        [projectorImage setHidden:TRUE];
        [projectorMovie setHidden:FALSE];
        [playPauseButton setEnabled:TRUE];
        [stopButton setEnabled:TRUE];
    }
}

- (void)windowDidResize:(NSNotification *)notification
{
    NSRect scrollVideosFrame = [windowView frame];
    scrollVideosFrame.size.width *= 0.2;
    if(scrollVideosFrame.size.width > 160)
    {
        scrollVideosFrame.size.width = 160;
    }
    scrollVideosFrame.size.height *= 0.3;
    scrollVideosFrame.origin.x = 0;
    scrollVideosFrame.origin.y = 0;
    [scrollVideos setFrame:scrollVideosFrame];
    
    NSRect scrollImagesFrame = [windowView frame];
    scrollImagesFrame.size.width = scrollVideosFrame.size.width;
    scrollImagesFrame.size.height -= scrollVideosFrame.size.height;
    scrollImagesFrame.origin.x = scrollVideosFrame.origin.x;
    scrollImagesFrame.origin.y = scrollVideosFrame.size.height;
    [scrollImages setFrame:scrollImagesFrame];
    
    NSRect scrollThumbnailsFrame = [windowView frame];
    scrollThumbnailsFrame.size.width -= (scrollImagesFrame.size.width + 10);
    scrollThumbnailsFrame.size.height = scrollImagesFrame.size.height;
    scrollThumbnailsFrame.origin.y = scrollVideosFrame.size.height;
    scrollThumbnailsFrame.origin.x = scrollImagesFrame.size.width + 5;
    [scrollThumbnails setFrame:scrollThumbnailsFrame];
    [thumbnailContainer setFrame:scrollThumbnailsFrame];
    
    NSRect lessWidthButtonframe = [lessWidthButton frame];
    lessWidthButtonframe.origin.x = scrollThumbnailsFrame.origin.x;
    lessWidthButtonframe.origin.y = scrollThumbnailsFrame.origin.y - lessWidthButtonframe.size.height;
    [lessWidthButton setFrame:lessWidthButtonframe];
    
    NSRect moreWidthButtonframe = [moreWidthButton frame];
    moreWidthButtonframe.origin.x = lessWidthButtonframe.origin.x + moreWidthButtonframe.size.width;
    moreWidthButtonframe.origin.y = lessWidthButtonframe.origin.y;
    [moreWidthButton setFrame:moreWidthButtonframe];
    
    NSRect lessHeightButtonframe = [lessHeightButton frame];
    lessHeightButtonframe.origin.x = lessWidthButtonframe.origin.x;
    lessHeightButtonframe.origin.y = lessWidthButtonframe.origin.y - lessHeightButtonframe.size.height;
    [lessHeightButton setFrame:lessHeightButtonframe];
    
    NSRect moreHeightButtonframe = [moreHeightButton frame];
    moreHeightButtonframe.origin.x = lessHeightButtonframe.origin.x + moreHeightButtonframe.size.width;
    moreHeightButtonframe.origin.y = lessHeightButtonframe.origin.y;
    [moreHeightButton setFrame:moreHeightButtonframe];
    
    NSRect lessZoomButtonframe = [lessZoomButton frame];
    lessZoomButtonframe.origin.x = lessHeightButtonframe.origin.x;
    lessZoomButtonframe.origin.y = lessHeightButtonframe.origin.y - lessZoomButtonframe.size.height;
    [lessZoomButton setFrame:lessZoomButtonframe];
    
    NSRect moreZoomButtonframe = [moreZoomButton frame];
    moreZoomButtonframe.origin.x = lessZoomButtonframe.origin.x + moreZoomButtonframe.size.width;
    moreZoomButtonframe.origin.y = lessZoomButtonframe.origin.y;
    [moreZoomButton setFrame:moreZoomButtonframe];
    
    NSRect leftButtonframe = [leftButton frame];
    leftButtonframe.origin.x = moreWidthButtonframe.origin.x + moreWidthButtonframe.size.width;
    leftButtonframe.origin.y = moreWidthButtonframe.origin.y;
    [leftButton setFrame:leftButtonframe];
    
    NSRect rightButtonframe = [rightButton frame];
    rightButtonframe.origin.x = leftButtonframe.origin.x + rightButtonframe.size.width;
    rightButtonframe.origin.y = leftButtonframe.origin.y;
    [rightButton setFrame:rightButtonframe];
    
    NSRect downButtonframe = [downButton frame];
    downButtonframe.origin.x = moreHeightButtonframe.origin.x + moreHeightButtonframe.size.width;
    downButtonframe.origin.y = moreHeightButtonframe.origin.y;
    [downButton setFrame:downButtonframe];
    
    NSRect upButtonframe = [upButton frame];
    upButtonframe.origin.x = downButtonframe.origin.x + upButtonframe.size.width;
    upButtonframe.origin.y = downButtonframe.origin.y;
    [upButton setFrame:upButtonframe];
    
    NSRect playPauseButtonframe = [playPauseButton frame];
    playPauseButtonframe.origin.x = moreZoomButtonframe.origin.x + moreZoomButtonframe.size.width;
    playPauseButtonframe.origin.y = moreZoomButtonframe.origin.y;
    [playPauseButton setFrame:playPauseButtonframe];
    
    NSRect stopButtonframe = [stopButton frame];
    stopButtonframe.origin.x = playPauseButtonframe.origin.x + stopButtonframe.size.width;
    stopButtonframe.origin.y = playPauseButtonframe.origin.y;
    [stopButton setFrame:stopButtonframe];
    
    NSRect blankButtonframe = [blankButton frame];
    blankButtonframe.origin.x = upButtonframe.origin.x + blankButtonframe.size.width;
    blankButtonframe.origin.y = upButtonframe.origin.y;
    [blankButton setFrame:blankButtonframe];
    
    [self redistributeImages];
}

- (void)addButtonForImage:(NSImage *)image
{
    [image setScalesWhenResized:true];

    CGFloat buttonWidth = 70.9*3.5;
    CGFloat buttonHeight = 28.3*3.5;
        
    NSRect buttonFrame = NSMakeRect(0, 0, buttonWidth, buttonHeight);
    
    NSButton* button = [[NSButton alloc] initWithFrame: buttonFrame];
    [[button cell] setTarget:self];
    [[button cell] setAction:@selector(imageClick:)];
    [[button cell] setImageScaling:NSImageScaleAxesIndependently];
    [button setImage:image];
    [button setHidden:false];
    
    [thumbnailContainer addSubview:button];
}

- (void)redistributeImages
{
    CGFloat buttonWidth = 70.9*3.5;
    CGFloat buttonHeight = 28.3*3.5;
    
    NSRect thumbnailFrame = [thumbnailContainer frame];
    NSRect scrollFrame = [scrollThumbnails frame];
    
    thumbnailFrame.size.width = scrollFrame.size.width;
    
    NSInteger imageCount = [[thumbnailContainer subviews] count];
    int imagesPerLine = MAX(thumbnailFrame.size.width / buttonWidth, 1);
    int neededLines = (int)ceil(imageCount / (double)imagesPerLine);
    thumbnailFrame.size.height = MAX(neededLines * (buttonHeight + 10), scrollFrame.size.height);
    
    [thumbnailContainer setFrame:thumbnailFrame];
    
    for(int i= 0;i<imageCount;i++)
    {
        int line = (i / imagesPerLine) + 1;
        int column = i % imagesPerLine;
        
        int x = column * (buttonWidth + 10);
        int y = thumbnailFrame.size.height - (line * (buttonHeight + 10));
        
        NSRect buttonFrame = NSMakeRect(x, y, buttonWidth, buttonHeight);
        
        [[[thumbnailContainer subviews] objectAtIndex:i] setFrame:buttonFrame];
    }
}

- (IBAction)movieActionClick:(id)sender
{
    NSLog(@"%@", [sender title]);
    
    if([[sender title] isEqualToString:@"Play"])
    {
        [projectorMovie play:self];
        [sender setTitle:@"Pause"];
        return;
    }
    
    if([[sender title] isEqualToString:@"Pause"])
    {
        [projectorMovie pause:self];
        [sender setTitle:@"Play"];
        return;
    }
    
    if([[sender title] isEqualToString:@"Stop"])
    {
        [playPauseButton setTitle:@"Play"];
        
        [projectorMovie pause:self];
        [projectorMovie gotoBeginning:self];
        return;
    }
}


- (IBAction)imageClick:(id)sender
{
    [projectorImage setImage:[sender image]];
    [projectorImage setHidden:FALSE];
}

-(IBAction)arrangementClick:(id)sender
{
    NSRect frame = projectorImage.frame;
    
    if([[sender title] isEqualToString:@"+ Largura"])
    {
        frame.size.width *= 1.1;
    }
    else if([[sender title] isEqualToString:@"- Largura"])
    {
        frame.size.width /= 1.1;
    }
    else if([[sender title] isEqualToString:@"+ Altura"])
    {
        frame.size.height *= 1.1;
    }
    else if([[sender title] isEqualToString:@"- Altura"])
    {
        frame.size.height /= 1.1;
    }
    else if([[sender title] isEqualToString:@"+ Zoom"])
    {
        frame.size.width *= 1.1;
        frame.size.height *= 1.1;
    }
    else if([[sender title] isEqualToString:@"- Zoom"])
    {
        frame.size.width /= 1.1;
        frame.size.height /= 1.1;
    }
    else if([[sender title] isEqualToString:@"Esquerda"])
    {
        frame.origin.x -= 5;
    }
    else if([[sender title] isEqualToString:@"Direita"])
    {
        frame.origin.x += 5;
    }
    else if([[sender title] isEqualToString:@"Cima"])
    {
        frame.origin.y += 5;
    }
    else if([[sender title] isEqualToString:@"Baixo"])
    {
        frame.origin.y -= 5;
    }
    
    [projectorImage setFrame:frame];
    [projectorMovie setFrame:frame];
}

- (IBAction) blank:(id)sender
{
    [projectorImage setHidden:TRUE];
    [projectorMovie setHidden:TRUE];
}

+ (id)getSortedContentsOf:(NSString *)folder
{
    NSError *error = nil;
    
    NSArray *content = [[[NSFileManager defaultManager] 
                     contentsOfDirectoryAtPath:folder error:&error] sortedArrayUsingSelector:@selector(compare:)];
    
    if(error != nil){
        [NSApp presentError:error];
    }
    
    NSMutableArray *ret = [[NSMutableArray alloc] initWithCapacity:[content count]];
    
    for(NSString *item in content){
        if([item rangeOfString:@"."].location == 0){
            continue;
        }
        [ret addObject:[item copy]];
    }
    
    return ret;
}

@end